package network;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicInteger;

public class NetworkPlayer implements Serializable, Comparable<NetworkPlayer> {
	
	private static final long serialVersionUID = 1L;
	private String name;
	private transient Socket socket;
	private int id;
	private static AtomicInteger ids= new AtomicInteger();
	/**
	 * @param name
	 */
	public NetworkPlayer(String name, Socket socket, int id) {
		super();
		this.name = name;
		this.setSocket(socket);
		this.id=NetworkPlayer.ids.getAndIncrement();
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param socket the socket to set
	 */
	public void setSocket(Socket socket) {
		this.socket = socket;
	}

	/**
	 * @return the socket
	 */
	public Socket getSocket() {
		return socket;
	}

	public boolean sendMsg(NetworkMsg msg){
		try {
			ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
			oos.writeObject(msg);
		} catch (IOException e) {
			return false;
		}
		return true;
	}

	public int compareTo(NetworkPlayer o) {
		if(o.id == id)
			return 0;
		else if(id > o.id)
			return 1;
		else
			return -1;
	}
	
	public boolean equals(Object o){
		if(o instanceof NetworkPlayer){
			if(compareTo((NetworkPlayer)o) == 0)
				return true;
		}
		return false;
	}

	public int getID() {
		return this.id;
	}
}
